package com.second.app.excutor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author GYZ
 * @Date 2024/1/24
 * <pre>
 *   队列使用SynchronousQueue类
 *   线程池中添加的数量>corePoolSize,将其余的任务也放入池中，总数量为8
 *   并且线程总数量也没有超过maximumPoolSize值8
 *   由于运行线程数为8,数量上 >corePoolSize为7的值
 *   所以keepAliveTime>5时，清除空闲线程
 *   如果使用synchronousQueue类则maximumPoolSize的参数作用有效
 * </pre>
 */
public class ThreadExecutorPool2Run {
    public static void main(String[] args) throws InterruptedException {

        Runnable runnable = () -> {
            try {
                System.out.println(Thread.currentThread().getName() + " run!" + System.currentTimeMillis());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(7, 8,
                5, TimeUnit.SECONDS, new SynchronousQueue<>());

        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);
        threadPoolExecutor.execute(runnable);

        Thread.sleep(300);
        //可以理解为：车中可载人的标准人数
        System.out.println("A:"+threadPoolExecutor.getCorePoolSize());
        //可以理解为：车中正在载的人数
        System.out.println("A:"+threadPoolExecutor.getPoolSize());
        //扩展车中正在载的人数
        System.out.println("A:"+threadPoolExecutor.getQueue().size());

        Thread.sleep(10000);
        System.out.println("B:"+threadPoolExecutor.getCorePoolSize());
        System.out.println("B:"+threadPoolExecutor.getPoolSize());
        System.out.println("B:"+threadPoolExecutor.getQueue().size());
    }
}
